package com.example.authority.controller;
import com.alibaba.excel.EasyExcel;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.read.listener.PageReadListener;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.authority.common.Result;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.List;
import java.time.LocalDateTime;


import com.example.authority.service.UserService;
import com.example.authority.entity.User ;
import com.example.authority.service.IncodeService;
import com.example.authority.entity.Incode;



/**
 * @program:   
 * @ClassName:IncodeController
 * @description: IncodeController前端控制器
 *       
 * @Version 3.0
 **/
@Tag(name = "邀请码管理 前端控制器")
    @RestController
@RequestMapping("/incode")
@Slf4j
    public class IncodeController {

@Resource
private IncodeService incodeService;
@Resource
private UserService userService;

/**
 * 新增
 * @param incode
 * @return
 */
@Operation(summary = "新增")
@PostMapping
public Result save(@RequestBody Incode incode){
        return Result.success(incodeService.save(incode));
        }
/**
* 修改
*
* @param incode
* @return
*/
@Operation(summary = "修改")
@PutMapping("/{id}")
public Result update(@PathVariable Long id,@RequestBody Incode incode) {
        return Result.success(incodeService.updateById(incode));
        }

/**
 * 查询所有Incode
 * @return
 */
@Operation(summary = "查询所有Incode")
@GetMapping
public Result findAll(){
        return Result.success(incodeService.list());
        }
/**
  * 获取单个
  * @param id
  * @return
  */
@Operation(summary = "获取单个")
@GetMapping("/{id}")
public Result findOne(@PathVariable Integer id){
        return Result.success(incodeService.getById(id));
        }
/**
 * 分页显示
 * @param
 * @param pageNum
 * @param pageSize
 * @return
 */
@Operation(summary = "分页显示")
@GetMapping("/page")
public Result findPage(
        @RequestParam(defaultValue = "") Long userid,
        @RequestParam(defaultValue = "") String invateCode,
@RequestParam(defaultValue = "1") Integer pageNum,
@RequestParam(defaultValue = "10") Integer pageSize){

        LambdaQueryWrapper<Incode>queryWrapper=new LambdaQueryWrapper();
        if (userid!=null&&userid!=0) {
            // name 不为空且不是空字符串的处理逻辑
            queryWrapper.eq(Incode::getUserid,userid);
        }
        if (StrUtil.isNotEmpty(invateCode)) {
            // name 不为空且不是空字符串的处理逻辑
            queryWrapper.like(Incode::getInvateCode,invateCode);
        }

        queryWrapper.orderByDesc(Incode::getId);
        Page<Incode>page=incodeService.page(new Page<>(pageNum,pageSize),queryWrapper);
        List<Incode > records = page.getRecords();
         for (Incode incode : records) {
                 User user = userService.getById(incode.getUserid());
                 if (ObjectUtil.isNotEmpty(user)){
                     incode.setUser(user);
                 }
         }
         page.setRecords(records);
         return Result.success(page);

        }
/**
* 单个删除
* @param id
* @return
*/
@Operation(summary = "单个删除")
@DeleteMapping("/{id}")
public Result delete(@PathVariable Integer id){
        return Result.success(incodeService.removeById(id));
        }
/**
* 批量删除
* @param ids
* @return
*/
@Operation(summary = "批量删除")
@DeleteMapping("/batch/{ids}")
@Transactional
public Result deleteByIds(@PathVariable String[]ids){
        return Result.success(incodeService.removeByIds(Arrays.asList(ids)));
        }

/**
 * 批量导出
 * 使用的技术为alibaba下面的easyexcel
 * 写数据
 *
 * @param ids
 * @return
 */
@Operation(summary = "批量导出")
@GetMapping("/batch/export/{ids}")
public void exportByIds(@PathVariable String[] ids, HttpServletResponse response) throws IOException {

        List<Incode> list = incodeService.listByIds(Arrays.asList(ids));
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("incode导出数据", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), Incode.class).sheet("sheel1").doWrite(list);

        }

/**
 * 批量导入
 * 使用的技术为alibaba下面的easyexcel
 * 读数据
 *
 * @param
 */
@Operation(summary = "批量导入")
@PostMapping("/batch/upload")
public Result writeExcel(MultipartFile file) throws IOException {
        EasyExcel.read(file.getInputStream(), Incode.class, new PageReadListener<Incode>(dataList -> {
        dataList.forEach(entity -> incodeService.save(entity.toBuilder().id(null).build()));
        })).sheet().doRead();
        return Result.success();
}
@GetMapping("/getThemselfIncode")
        public Result getThemselfIncode(@RequestParam Long id){
        log.info("传递进来的用户id："+id);

        Incode one = incodeService.getOne(new LambdaQueryWrapper<Incode>().eq(Incode::getUserid, id));
        return Result.success(one);
        }
@GetMapping("/generateIncode")
        public Result generateIncode(@RequestParam Long id) {
            // 获取最后一条记录
            LambdaQueryWrapper<Incode> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.orderByDesc(Incode::getId);
            queryWrapper.last("LIMIT 1");
            Incode lastIncode = incodeService.getOne(queryWrapper);

            // 创建新的邀请码记录
            Incode incode = new Incode();
            incode.setUserid(id);
            
            // 生成新的邀请码
            String newCode;
            if (lastIncode != null && lastIncode.getInvateCode() != null) {
                // 获取最后一条记录的邀请码并加1
                String lastCode = lastIncode.getInvateCode();
                int codeNumber = Integer.parseInt(lastCode) + 1;
                newCode = String.format("%06d", codeNumber); // 保持6位数字格式
            } else {
                // 如果没有记录，从1开始
                newCode = "000001";
            }
            
            incode.setInvateCode(newCode);
            incode.setCreateTime(LocalDateTime.now());
            
            // 保存新记录
            incodeService.save(incode);
            
            return Result.success(incode);
        }

}